<template>
  <div class="activity-page">
    <div class="router-content">
      <div v-if="pageType == 'list'">
        <QueryBar
          :queryForm="queryForm"
          :queryConfig="queryBar"
          @handleQueryClick="handleQueryClick"
        />
        <div style="margin-bottom: 20px">
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="addList"
            v-if="add"
            >新增协会活动</el-button
          >
        </div>
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="50">
            <template slot-scope="scope">{{
              10 > scope.$index + 1
                ? "0" + (scope.$index + 1)
                : scope.$index + 1
            }}</template>
          </el-table-column>
          <el-table-column prop="imageUrl" label="协会活动封面">
            <template slot-scope="scope">
              <img
                v-if="scope.row.activityCover"
                style="width: 72px; height: 40px"
                :src="scope.row.activityCover"
                alt
              />
              <img
                v-else
                src="@/assets/noImg.jpg"
                style="width: 72px; height: 40px"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="activityTitle"
            label="协会活动标题"
          ></el-table-column>
          <el-table-column prop="state" label="活动时间" width="350">
            <template slot-scope="scope">
              {{ scope.row.startTime | formatTime }} 至
              {{ scope.row.endTime | formatTime }}</template
            >
          </el-table-column>
          <el-table-column prop="activityState" label="活动状态">
            <template slot-scope="scope">
              {{
                scope.row.activityState == 1
                  ? "预约中"
                  : scope.row.activityState == 2
                  ? "已结束"
                  : ""
              }}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="发布状态">
            <template slot-scope="scope">
              {{
                scope.row.state == 1
                  ? "待发布"
                  : scope.row.state == 2
                  ? "已发布"
                  : scope.row.state == 3
                  ? "已撤回"
                  : ""
              }}
            </template>
          </el-table-column>
          <el-table-column prop="publishTime" label="发布时间">
            <template slot-scope="scope">
              {{ scope.row.publishTime | formatTime }}
            </template>
          </el-table-column>
          <el-table-column prop="createName" label="操作人"></el-table-column>
          <el-table-column label="操作" :width="188">
            <template slot-scope="scope">
              <el-tag
                v-if="query"
                @click="handleOptions({ key: '1', index: scope.$index })"
                size="medium"
                style="margin: 0 5px 0 0; cursor: pointer"
                >详情</el-tag
              >
              <el-tag
                v-if="edit"
                @click="handleOptions({ key: '2', index: scope.$index })"
                size="medium"
                style="margin: 0 5px 0 0; cursor: pointer"
                >编辑</el-tag
              >
              <!-- <el-tag
                v-if="scope.row.state == 2 && revoke"
                @click="handleOptions({ key: '3', index: scope.$index })"
                size="medium"
                style="margin: 0 5px 0 0; cursor: pointer"
                >撤回</el-tag
              > -->
              <el-tag
                v-if="del"
                @click="handleOptions({ key: '4', index: scope.$index })"
                size="medium"
                style="cursor: pointer"
                >删除</el-tag
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 50px"
          @current-change="handlePageChange"
          :current-page="pageParams.pageNum"
          :page-sizes="[pageParams.pageSize]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        ></el-pagination>
      </div>
      <div v-else>
        <div
          v-if="
            pageType == 'add' || pageType == 'edit' || pageType == 'details'
          "
        >
          <el-form
            label-width="120px"
            :model="formModel"
            :rules="formRules"
            ref="formModel"
            style="width: 80%; margin: 32px auto"
          >
            <el-form-item label="协会活动标题" prop="activityTitle">
              <el-input
                :disabled="pageType == 'details'"
                maxlength="64"
                v-model="formModel.activityTitle"
                placeholder="请输入协会活动标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="协会活动封面" prop="activityCover">
              <el-upload
                accept=".png, .jpeg, .jpg, .gif"
                action
                :disabled="pageType == 'details'"
                :http-request="uploadOss"
                :show-file-list="false"
                :before-upload="handleBeforeUpload"
              >
                <div v-if="formModel.activityCover">
                  <img :src="formModel.activityCover" class="avatar" />
                </div>
                <div v-else class="notImg">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <span>上传封面图</span>
                </div>
              </el-upload>
              <p style="color: #666">
                仅支持png、jpg、gif、jpeg格式，不超过2m（尺寸比列4：3)
              </p>
            </el-form-item>
            <el-form-item label="举办方" prop="activityOrganizer">
              <el-input
                :disabled="pageType == 'details'"
                maxlength="32"
                v-model="formModel.activityOrganizer"
                placeholder="请输入举办方"
              ></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="activityAddress">
              <el-input
                :disabled="pageType == 'details'"
                maxlength="256"
                v-model="formModel.activityAddress"
                placeholder="请输入地址"
              ></el-input>
            </el-form-item>
            <el-form-item label="活动时间" prop="startTime">
              <el-date-picker
                :disabled="pageType == 'details'"
                v-model="timeRange"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="['00:00:00']"
                @change="timeChange"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="预约电话" prop="bookingLine">
              <el-input
                :disabled="pageType == 'details'"
                maxlength="11"
                v-model="formModel.bookingLine"
                placeholder="请输入预约电话"
              ></el-input>
            </el-form-item>
            <el-form-item label="协会活动内容" prop="activityContent">
              <quill-editor
                :disabled="pageType == 'details'"
                v-model="formModel.activityContent"
                :options="options"
                class="ql-editor ql-box"
                @change="onEditorChange"
              />
            </el-form-item>
            <el-form-item label="活动推荐" prop="recommended">
              <el-checkbox
                :disabled="pageType == 'details'"
                v-model="formModel.recommended"
                >推荐</el-checkbox
              >
            </el-form-item>
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                :disabled="pageType == 'details'"
                style="width: 400px"
                v-model="formModel.publishTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                @change="handleTime"
                align="center"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label>
              <el-button
                v-if="pageType != 'details'"
                type="primary"
                @click="submitForm('formModel')"
                :loading="$store.state.subLoading"
                >提交</el-button
              >
              <el-button
                v-if="pageType != 'details'"
                @click="closeForm('formModel')"
                >取消</el-button
              >
              <el-button
                v-if="pageType == 'details'"
                type="primary"
                @click="pageType = 'list'"
                :loading="$store.state.subLoading"
                >返回</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
      <Modal
        :title="
          modalType == 'del'
            ? '删除确认'
            : modalType == 'revoke'
            ? '撤回确认'
            : ''
        "
        :dialogVisible="visible"
        :loading="$store.state.subLoading"
        @handleClose="handleCancel"
        @handleConfirm="handleConfirm"
        width="600px"
      >
        <div v-if="modalType == 'del'">
          <i
            class="el-icon-warning"
            style="color: #faad14; font-size: 18px; margin: 0 20px"
          ></i
          >确认要删除该条协会活动内容吗？
        </div>
        <div v-else>
          <i
            class="el-icon-warning"
            style="color: #faad14; font-size: 18px; margin: 0 20px"
          ></i
          >确认要从官网撤回该条协会活动内容吗？
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import { toolBars, handlers } from "@/utils/ToolBars.js";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import QueryBar from "@/components/common/QueryBar.vue";
import Modal from "@/components/common/Modal.vue";
import { queryBar } from "./configuration/activity";
import api from "@/api/modules/dynamic/activity.js";
import util from "@/utils";
import setToken from "@/utils/auth";
export default {
  name: "Activity",
  components: { QueryBar, Modal, quillEditor },
  data() {
    return {
      query: true,
      add: true,
      edit: true,
      // revoke: true,
      del: true, //按钮权限
      pickerOptions: {
        // disabledDate: (time) => {
        //   return time.getTime() < Date.now() - 1 * 24 * 3600 * 1000;
        // },
      },
      pageType: "list",
      modalType: "",
      visible: false,
      queryForm: {},
      queryBar: queryBar,
      currentRow: "",
      tableData: [],
      count: 0,
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },

      //
      detailsData: "",
      timeRange: "",
      formModel: {
        activityTitle: "", //标题
        activityCover: ``, //封面
        activityOrganizer: "", //举办方
        bookingLine: "", //预约电话
        activityContent: "", //内容
        publishTime: "", //发布时间
        activityAddress: "", //地址
        startTime: "",
        endTime: "",
        recommended: false,
      },
      formRules: {
        activityTitle: [
          { required: true, message: "请输入协会活动标题", trigger: "blur" },
        ],
        activityCover: [{ message: "请上传封面", trigger: "blur" }],
        activityOrganizer: [
          { required: true, message: "请输入举办方", trigger: "blur" },
        ],
        activityAddress: [
          { required: true, message: "请输入活动地址", trigger: "blur" },
        ],
        activityContent: [
          {
            required: true,
            message: "请输入协会活动内容",
            trigger: "blur",
          },
        ],
        publishTime: [
          { required: true, message: "请选择更新时间", trigger: "blur" },
        ],
        bookingLine: [
          {
            required: true,
            pattern: /^1([3456789])\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        startTime: [
          { required: true, message: "请选择活动时间", trigger: "blur" },
        ],
      },
      options: {
        placeholder: "请输入...",
        modules: { toolbar: { container: toolBars, handlers: handlers } },
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      // 设置页面按钮权限
      let btns = this.$store.state.userInfo.list[1].children[4].children;
      console.log(btns);
      this.query = btns[0].havePermission;
      this.add = btns[1].havePermission;
      this.edit = btns[2].havePermission;
      this.del = btns[3].havePermission;

      this.getData(this.pageParams);
    });
  },
  methods: {
    timeChange() {
      if (this.timeRange) {
        this.formModel.startTime = this.timeRange[0];
        this.formModel.endTime = this.timeRange[1];
      }
    },
    getData(params) {
      try {
        api
          .getAssociationActivityPage(
            params ? params : { ...this.pageParams, ...this.queryForm }
          )
          .then((res) => {
            this.tableData = res.data;
            this.count = +res.count;
            this.pageType = "list";
          });
      } catch (error) {}
      this.modalType = "";
      this.visible = false;
    },
    handlePageChange(val) {
      this.pageParams.pageNum = val;
      this.getData({ ...this.pageParams, ...this.queryForm });
    },
    handleQueryClick(val) {
      switch (val) {
        case "search":
          if (this.queryForm.timeRange) {
            let obj = {
              activityTitle: this.queryForm.activityTitle,
              state: this.queryForm.state,
              startTime: util.formatTime(this.queryForm.timeRange[0]),
              endTime: util.formatTime(this.queryForm.timeRange[1]),
            };
            this.pageParams.pageNum = 1;
            this.getData({ ...this.pageParams, ...obj });
          } else {
            this.pageParams.pageNum = 1;
            this.getData({ ...this.pageParams, ...this.queryForm });
          }
          break;
        case "reset":
          Object.keys(this.queryForm).forEach((item) => {
            this.queryForm[item] = "";
          });
          this.pageParams.pageNum = 1;
          this.getData(this.pageParams);
          break;
      }
    },
    handleOptions(val) {
      const { key, index } = val;
      this.currentRow = this.tableData[index];
      switch (key) {
        case "1":
          api
            .getAssociationActivity({
              associationActivityId: this.currentRow.associationActivityId,
            })
            .then((res) => {
              Object.keys(res.data).forEach((item) => {
                this.formModel[item] = this.currentRow[item];
              });
              this.formModel.recommended = res.data.recommended;
              this.formModel.activityContent = res.data.activityContent;
              this.timeRange = [
                this.formModel["startTime"],
                this.formModel["endTime"],
              ];
              this.pageType = "details";
            });
          break;
        case "2":
          api
            .getAssociationActivity({
              associationActivityId: this.currentRow.associationActivityId,
            })
            .then((res) => {
              Object.keys(res.data).forEach((item) => {
                this.formModel[item] = this.currentRow[item];
              });
              this.formModel.recommended = res.data.recommended;
              this.formModel.activityContent = res.data.activityContent;
              this.formModel.publishTime = new Date(this.formModel.publishTime);
              this.timeRange = [
                this.formModel["startTime"],
                this.formModel["endTime"],
              ];
              this.pageType = "edit";
            });

          break;
        case "3":
          this.modalType = "revoke";
          this.visible = true;
          break;
        case "4":
          this.modalType = "del";
          this.visible = true;
          break;
      }
    },
    handleCancel() {
      this.visible = false;
    },
    handleConfirm() {
      if (this.modalType == "del") {
        if (this.pageParams.pageNum != 1 && this.tableData.length == 1) {
          this.pageParams.pageNum = this.pageParams.pageNum - 1;
        }
        api
          .deleteAssociationActivity({
            associationActivityId: this.currentRow.associationActivityId,
          })
          .then((res) => {
            this.$message.success("删除成功");
            this.getData({ ...this.pageParams, ...this.queryForm });
          });
      } else {
        api
          .revokeAssociationActivity({
            associationActivityId: this.currentRow.associationActivityId,
          })
          .then((res) => {
            this.$message.success("撤回成功");
            this.getData({ ...this.pageParams, ...this.queryForm });
          });
      }
    },
    addList() {
      Object.keys(this.formModel).forEach((item) => {
        this.formModel[item] = "";
      });
      this.timeRange = "";
      this.pageType = "add";
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formModel.startTime = util.formatTime(this.formModel.startTime);
          this.formModel.endTime = util.formatTime(this.formModel.endTime);
          this.formModel.publishTime = util.formatTime(
            this.formModel.publishTime
          );
          this.$store.commit("setSubLoading", true);
          if (this.pageType == "add") {
            api.addAssociationActivity(this.formModel).then((res) => {
              this.$message.success("添加成功");
              this.pageParams.pageNum=1
              this.getData();
            });
          } else {
            api
              .modifyAssociationActivity({
                ...this.formModel,
                ...{
                  associationActivityId: this.currentRow.associationActivityId,
                },
              })
              .then((res) => {
                this.$message.success("修改成功");
                this.getData();
              });
          }
        } else {
          return false;
        }
      });
    },
    closeForm(formName) {
      this.$refs[formName].resetFields();
      this.pageType = "list";
    },
    handleTime() {
      // var startAt = (new Date(this.formModel.publishTime) * 1000) / 1000;
      // if (startAt < Date.now()) {
      //   this.formModel.publishTime = new Date();
      // }
    },
    handleBeforeUpload(file) {
      console.log(file);
      if (file.type.split("/")[0] != "image") {
        this.$message.error("请上传图片格式文件");
        return false;
      }
      if (file.size > 2097152) {
        this.$message.error("上传图片大小不能超出2M");
        return false;
      }
    },
    uploadOss(file) {
      let formData = new FormData();
      let token = setToken.getToken();
      formData.append("file", file.file, file.file.name);
      this.$http({
        method: "post",
        url: "/api/upload",
        data: formData,
        headers: { Authorization: "Bearer " + token },
      })
        .then((res) => {
          this.formModel.activityCover = res.data.data;
          this.$refs["formModel"].validateField("activityCover");
        })
        .catch((error) => {
          this.$message.error("系统错误");
        });
    },
    onEditorChange() {
      this.$refs["formModel"].validateField("activityContent");
    },
  },
};
</script>
<style lang="less" >
.activity-page {
  // .ql-editor {
  //   width: 100%;
  //   padding: 0;
  //   min-height: 344px;
  //   line-height: normal !important;
  //   overflow: hidden;
  // }
  .el-upload,
  .el-upload--picture-card {
    width: 104px;
    height: 104px;
    line-height: 60px;
    box-sizing: border-box;
    border: 1px dashed #666;
    border-radius: 5px;
    overflow: hidden;
    img {
      width: 104px;
      height: 104px;
    }
  }
  .hasImg,
  .notImg {
    width: 102px;
    height: 102px;
    background-color: #f0f2f5;

    position: relative;
  }
  .notImg {
    padding-top: 35px;
    box-sizing: border-box;
    i {
      display: block;
      font-size: 16px;
      line-height: 10px;
    }
    span {
      display: block;
    }
  }
}
</style>
